<template>
  <Spin :spinning="loading1" tip="Loading...">
    <div>
      <!-- 备件保修类型维护 -->
      <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="4" labelWidth="90" @filterChange="changeHandle">
      </TopFilter>
      <!-- table -->
      <Spin :spinning="loading" tip="导入中，请稍后...">
        <FilterTable ref="table" :columns="columns" :params="fetchParams" :fetchapi="fetchapi" :datakey="'records'"
          :onColumnsChange="(columns) => (this.columns = columns)" :onRowSelectChange="selectChange">
          <template slot="controls" slot-scope="props">
            <multiuse-button size="small" type="primary" icon="el-icon-check" :click="qiyong.bind()"
              :disabled="disableds">启用</multiuse-button>
            <multiuse-button size="small" type="primary" icon="el-icon-close" :click="tingyong.bind()"
              :disabled="disableds">停用</multiuse-button>
            <!-- <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">新增</multiuse-button> -->
            <multiuse-button type="primary" :click="exportFileBtn.bind()">导出</multiuse-button>
            <!--            <multiuse-button size="small" type="primary" :click="downloadTemplate.bind()">下载模板</multiuse-button>-->
            <el-button size="small" type="primary" icon="el-icon-plus" @click="openimportPjDialog()">数据导入</el-button>
          </template>
        </FilterTable>
      </Spin>
      <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose
        :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <Vehicle @close="close" @save="save"></Vehicle>
      </BaseDialog>
      <!-- <BaseDialog :visible.sync="visibleAdd" :title="'备件保修类型新增'" width="850px" destroyOnClose
        :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <AddForm @close="closeAdd" @save="saveAdd"></AddForm>
      </BaseDialog> -->
      <BaseDialog :visible.sync="visibleEdit" :title="'备件保修类型维护'" width="850px" destroyOnClose
        :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <EditForm :rowData="rowData" @close="editclose" @save="editsave"></EditForm>
      </BaseDialog>
      <BaseDialog style="min-height: 80vh;" :visible.sync="visibleImportPeij" width="80vw" title="备件保修类型导入"
        destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }">
        <ExcelImport ref="import" template-file-name="备件保修类型导入模板.xlsx" :importRules="importRules"
          :onComplete="importComplete" @close="visibleImportPeij = false" />
      </BaseDialog>
    </div>
  </Spin>
</template>
<script>
import { getToken, getAppId, getUserId } from '@/assets/js/auth';
import { getListByPage, piliangqiyong, piliangtingyong, downloadModel, getListForExport, importPartList } from '@/api/claim/factory/PartWarrantyType/index.js';
import importExcel from '@/pages/claimDemage/tools/importExcel.vue';
//import AddForm from './addForm.vue';
import Vehicle from '@/pages/claimDemage/tools/ModelVehicle.vue';
import EditForm from './editForm.vue';
import { exportExcelFile } from '@/utils/index';
import { dictionary } from '@/utils/dictMixin';
import ExcelImport from '@/components/ExcelImport';
export default {
  props: {},
  mixins: [dictionary],
  components: {
    Vehicle,
    // AddForm,
    EditForm,
    importExcel,
    ExcelImport,
  },
  data() {
    return {
      dataList: [],
      rowData: {},
      params: {},
      visible: false,
      disableds: true,
      showImport: false,
      //  collapse: false,  //收起显示与否
      visibleEdit: false,
      visibleImportPeij: false,
      fetchapi: getListByPage,
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      dialogTitle: '选择车辆',
      // visibleAdd: false,
      headersObj: {
        jwt: getToken(),
        appId: getAppId(),
        userId: getUserId(),
        userAgent: 'pc',
      },
      loading: false,
      loading1: false,
      fileList: [],
      importRules: [
        { prop: 'partCode', title: '备件代码', rule: { required: true, message: '备件代码不能为空', } },
        { prop: 'partName', title: '备件名称', },
       /*  { prop: 'channelCode', title: '采购渠道代码', rule: { required: true, message: '采购渠道代码不能为空' } },
        { prop: 'channelName', title: '采购渠道名称', }, */
        { prop: 'supplierCode', title: '供应商编码', },
        { prop: 'manageRate', title: '备件管理费率%', rule: { required: true, message: '备件管理费率不能为空' } },
        { prop: 'warrantyType', title: '备件类型', rule: [{ itemList: this.createDictList('5509',) }, { required: true, message: '备件类型不能为空' }] },
        { prop: 'returnType', title: '返件类型', rule: [{ itemList: this.createDictList('5585', [55851002]) }, { required: true, message: '返件类型不能为空' }] },
        { prop: 'isSpecially', title: '是否特批', rule: [{ itemList: this.createDictList('1004') }, { required: true, message: '是否特批不能为空' }] },
        { prop: 'isAccessories', title: '是否辅料', rule: [{ itemList: this.createDictList('1004') }, { required: true, message: '是否辅料不能为空' }] },
        { prop: 'isAttached', title: '是否附件', rule: [{ itemList: this.createDictList('1004') }, { required: true, message: '是否附件不能为空' }] },
        { prop: 'series', title: '适用车型', },
       /*  { prop: 'ptStatusStr', title: '状态',  rule: [{ itemList: this.createDictList('1004') },{ required: true, message: '状态不能为空' }] }, */
        { prop: 'isScrapStr', title: '是否报废', rule: [{ itemList: this.createDictList('1004') }, { required: true, message: '是否报废不能为空' }] },
      ]
    };
  },
  created() {
    this.chuqi();

  },
  methods: {
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      this.disableds = this.selectedRows.length <= 0;
      console.log(this.selectedRows);
    },
    async chuqi() {

    },
    // Excel更新导入
    showImportFun() {
      this.showImport = true;
    },
    //下载模板
    downloadTemplate() {
      this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        downloadModel().then((res) => {
          console.log(res);
          exportExcelFile(res.data, '备件保修类型导入模板');
        });
      });
    },
    // 导出
    async exportFileBtn() {
      this.loading1 = true;
      getListForExport(this.fetchParams).then((res) => {
        exportExcelFile(res.data, '备件保修类型维护');
        console.log('res.data',res.data)
        this.loading1 = false;
      });
    },
    showErrorList(response) {
      if (response.resultCode == 200) {
        this.$notify.success({ title: '提示信息', message: '导入完成!' });
        this.fetchParams = { ...this.fetchParams };
        this.fileList = [];
        this.loading = false;
      } else {
        this.fileList = [];
        this.$notify.error({ title: '提示信息', message: response.errMsg });
        this.loading = false;
      }
    },
    handleExceed(error) {
      this.loading = false;
    },
    beforeUpload() {
      this.loading = true;
    },
    /* 打开导入配件Dialog */
    openimportPjDialog() {
      this.visibleImportPeij = true;
    },
    //导入
    async importComplete(datas, callback) {
      const errorData = [];
      console.info(datas,'datas');
      datas.forEach((item, index1) => {
        const indexarr = [];
        datas.forEach((i, index2) => {
          if (i.partCode === item.partCode && index1 !== index2) {
            indexarr.push(index2 + 1);
          }
        });
        if (indexarr.length) {
          errorData.push({
            rownum: index1 + 1,
            errormsg: `与第${indexarr.join(',')}行备件信息重复`
          });
        }
      });

      if (errorData.length) {
        callback(errorData);
      } else {
        importPartList(datas).then(res => {
          if (res.resultCode == 200) {
            if (res.data.status) {
              this.visibleImportPeij = false;
              this.$notify.success({ title: '提示信息', message: '批量导入成功' });
              callback();
              this.infoClose({ type: 'refresh' });
            } else {
              callback(res.data.errorData);
            }
          } else {
            callback([{ errormsg: '服务器运行异常' }]);
          }
        });
      }
    },
    //批量启用
    async qiyong() {
      if (this.selectedRows.length > 0) {
        //当适用车型为空时，不给启用
        for (var i = 0; i < this.selectedRows.length; i++) {
          if (this.selectedRows[i].series == null || this.selectedRows[i].series == '') {
            this.$notify.warning({ title: '提示信息', message: '备件代码' + this.selectedRows[i].partCode + '的适用车型为空不允许启用' });
          }
          else {
            let str = '';
            str += this.selectedRows[i].id + ',';
            const res = await piliangqiyong({ ids: str, status: '10041001' });
          }
        }
        // console.log('----------------',this.selectedRows)
        // const res = await piliangqiyong({ ids: str, status: '10041001' });
        this.fetchParams = { ...this.fetchParams };
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行启用！' });
      }
    },
    //批量停用
    async tingyong() {
      if (this.selectedRows.length > 0) {
        let str = '';
        this.selectedRows.map((x) => {
          str += x.id + ',';
        });
        const res = await piliangtingyong({ ids: str, status: '10041002' });
        this.fetchParams = { ...this.fetchParams };
        this.loading = false;
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行禁用！' });
      }
    },
    /* add() {
      this.visibleAdd = true;
    }, */
    /* closeAdd() {
      this.visibleAdd = false;
    },
    saveAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    }, */
    editclose() {
      this.visibleEdit = false;
    },
    emitFun(val) {
      this.rowData = val;
      console.log('val', val)
      this.visibleEdit = true;
    },
    editsave() {
      this.visibleEdit = false;
      this.fetchParams = { ...this.fetchParams };
    },
    editsave1() {
      this.showImport = false;
      this.fetchParams = { ...this.fetchParams };
    },
    close() {
      this.visible = false;
    },
    chooseOrderNo() {
      this.visible = true;
    },
    save(obj) {
      this.topFilterInit.find((x) => x.fieldName == 'model').initialValue = obj[0].address;
      this.visible = false;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign({}, this.fetchParams, val);
      console.log(val);
    },
    //搜索数据
    topFilterInitFun() {
      // 备件代码、备件名称、备件类型、、是否特批、是否辅料、是否附件、是否停用
      return [
        {
          type: 'INPUT',
          label: '备件代码',
          fieldName: 'partCode',
          placeholder: '请输入',
          initialValue: '',
        },
        {
          type: 'INPUT',
          label: '备件名称',
          fieldName: 'partName',
          placeholder: '请输入.',
          initialValue: '',
        },
        {
          type: 'SELECT',
          label: '备件类型',
          fieldName: 'warrantyType',
          placeholder: '请选择',
          initialValue: '',
          filterable: true,
          itemList: this.createDictList('5509')
        },
        {
          type: 'SELECT',
          label: '返件类型',
          fieldName: 'returnType',
          placeholder: '请选择',
          initialValue: '',
          filterable: true,
          itemList: this.createDictList('5585', [55851002])
        },
        {
          type: 'SELECT',
          label: '是否特批',
          placeholder: '请选择...',
          fieldName: 'isSpecially',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '是否辅料',
          placeholder: '请选择...',
          fieldName: 'isAccessories',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '是否附件',
          placeholder: '请选择...',
          fieldName: 'isAttached',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '状态',
          placeholder: '请选择...',
          fieldName: 'ptStatus',
          itemList: [
            { text: '启用', value: 10041001 },
            { text: '停用', value: 10041002 }
          ],
        },
        {
          type: 'INPUT',
          label: '采购渠道代码',
          fieldName: 'channelCode',
          placeholder: '请填写采购渠道代码...',
          initialValue: '',
        },
        {
          type: 'INPUT',
          label: '采购渠道名称',
          fieldName: 'channelName',
          placeholder: '请填写采购渠道名称...',
          initialValue: '',
        },
        {
          type: 'SELECT',
          label: '是否报废',
          fieldName: 'isScrap',
          initialValue: '',
          itemList: [
            { text: '是', value: 10041001 },
            { text: '否', value: 10041002 }
          ],
        },
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          fixed: 'left',
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          render: (props, h) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.emitFun(props.row)}>
                  编辑
                </multiuse-button>
              </div>
            );
          },
        },
        { title: '备件代码', dataIndex: 'partCode', sorter: true, width: 180 },
        { title: '备件名称', dataIndex: 'partName', sorter: true, width: 180 },
        { title: '索赔价', dataIndex: 'claimPrice', sorter: true },
        { title: '索赔价生效日期', dataIndex: 'claimPriceDate', sorter: true },
        {
          title: '备件管理费率%', dataIndex: 'manageRate', sorter: true, render: (props) => {
            return <span>{parseFloat(props.row.manageRate * 100).toFixed(2)}</span>;
          },
        },
        { title: '采购渠道代码', dataIndex: 'channelCode', sorter: true },
        { title: '采购渠道名称', dataIndex: 'channelName', sorter: true, width: 200 },
        { title: '供应商编码', dataIndex: 'supplierCode', sorter: true },
        { title: '备件类型', dataIndex: 'warrantyType', sorter: true, dictItems: this.createDictList('5509') },
        { title: '是否特批', dataIndex: 'isSpeciallyStr', sorter: true, width: 120 },
        { title: '返件类型', dataIndex: 'returnType', sorter: true, width: 120, dictItems: this.createDictList('5585', [55851002]) },
        { title: '是否辅料', dataIndex: 'isAccessoriesStr', sorter: true, width: 120 },
        { title: '是否附件', dataIndex: 'isAttachedStr', sorter: true, width: 120 },
        { title: '适用车型', dataIndex: 'series', sorter: true },
        { title: '状态', dataIndex: 'ptStatusStr', sorter: true },
        {
          title: '是否报废', dataIndex: 'isScrapStr', sorter: true, dictItems: [
            { text: '是', value: 10041001 },
            { text: '否', value: 10041002 },
          ],
        },
      /*   { title: '创建人', dataIndex: 'createdBy', sorter: true },
        { title: '创建时间', dataIndex: 'createdAt', sorter: true, width: 220 }, */
        { title: '修改人', dataIndex: 'updatedBy', sorter: true },
        { title: '修改时间', dataIndex: 'updatedAt', sorter: true, width: 220 }
      ];
    },
  },
};
</script>

<style lang="less" scoped>

</style>
